<template>
    <a-drawer v-model:open="state.open" placement="right" width="35%" :closable="false" @close="handleCancle">
        <template #title>
            <div class="flex">
                <edit-title v-model="conditionConfig.name" />
                <setting-item-box name="优先级:">
                    <a-input-number v-model:value="conditionConfig.priorityLevel" :min="1" placeholder="优先级"/>
                </setting-item-box>
                <setting-item-box name="默认条件:">
                    <a-switch v-model:checked="conditionConfig.defaultCondition" :checkedValue="true" :unCheckedValue="false" @change="handleSwitchChange"/>
                </setting-item-box>
            </div>
        </template>
        <div class="condition-drawer-content">
            <div class="mb-2">满足以下条件时进入当前分支</div>
            <div class="condition-group-list mb-2">
                <a-card 
                    class="condition-group-item mb-2" 
                >
                    <div class="condition-group-item-title flex justify-between">
                        条件集合
                    </div>
                    <div class="condition-list">
                        <div 
                            class="condition-item"
                            v-for="(condition,index) in conditionConfig.conditions" 
                            :key="condition.id"    
                        >
                            <div class="condition-item-title mb-2 flex justify-between">
                                <span>
                                    {{ index == 0 ? "条件1" : `且满足条件${index + 1}` }}
                                </span>
                                <DeleteOutlined class="cursor-pointer" @click="deleteCondition(condition.id)"/>
                            </div>
                            <div class="w-full">
                                <a-select v-model:value="condition.varName" class="w-full  mb-2" allowClear @change="onConditionChange($event,condition)">
                                    <a-select-option 
                                        v-for="c in state.conditionOptions"
                                        :key='c.name'
                                        :value="c.name"
                                    >
                                        {{ c.label }}
                                    </a-select-option>
                                </a-select>
                                <!-- 运算符 -->
                                <template v-if="condition.varName && Array.isArray(condition.operators)">
                                    <a-select v-model:value="condition.operator" class="w-full  mb-2" allowClear>
                                        <a-select-option 
                                            v-for="(o,index) in condition.operators"
                                            :key="index"
                                            :value="o"
                                        >
                                            {{getOptName(o)}}
                                        </a-select-option>
                                    </a-select>
                                </template>
                                <!-- 发起人才可以选机构，角色，用户 -->
                                <template v-if="condition.varName == FlowConditionTypeEnum.USER_ID">
                                    <a-input :value="getValName(condition.val)" placeholder="" readonly>
                                        <template #suffix>
                                            <a-button type="link" @click="selectOrgRoleUser(condition)">添加</a-button>
                                        </template>
                                    </a-input>
                                </template>
                            </div>
                        </div>
                        <a-button type="link" @click="addCondition">添加条件</a-button>
                    </div>
                </a-card>
            </div>
        </div>
        <template #footer>
            <section class="flow-btn-box">
                <a-button @click="handleCancle">取消</a-button>
                <a-button type="primary" @click="save">保存</a-button>
            </section>
        </template>
        <select-dept-role-user ref="selectOrgRoleUserRef" @selected="getSelected"/>
    </a-drawer>
</template>

<script setup lang="ts">
import { reactive, useTemplateRef } from 'vue';
import editTitle from './editTitle.vue';
import type { ConditionItemType, ConditionNodeType, ConditionProperties } from '../types';
import type LogicFlow from '@logicflow/core';
import { getFieldLabel, getOptName, getUUID, getValName } from '@/utils';
import settingItemBox from '@/components/chart/settingItemBox/index.vue'
import { FlowConditionTypeEnum } from '@/enum/flowEnum';
import selectDeptRoleUser from '@/components/select-dept-role-user/index.vue'

// @ts-ignore
let conditionConfig = reactive<ConditionProperties>({})
const selectOrgRoleUserRef = useTemplateRef('selectOrgRoleUserRef')
const state = reactive<{
    open: boolean,
    lf: LogicFlow | null,
    activeNode: ConditionNodeType
    conditionOptions:any[], //条件发起人列表
    curCondition:ConditionItemType | null
}>({
    open: false,
    lf: null,
    // @ts-ignore
    activeNode: null,
    conditionOptions:[]
})

const initData = ()=>{
    // 初始化条件发起人列表
    state.conditionOptions= [
        {
            id:getUUID(),
            label:'发起人',
            name:FlowConditionTypeEnum.USER_ID,
            operators:[6,7] //条件操作符
        }
    ]
    // 遍历表单设计字段添加到条件发起人列表
}

const handleOpen = (node: any, lf: LogicFlow) => {
    state.open = true
    state.activeNode = node
    Object.assign(conditionConfig, node.properties)
    state.lf = lf
    initData()
}
const handleCancle = () => {
    state.open = false
    conditionConfig = reactive({})
    state.activeNode = null
    state.lf = null
    state.conditionOptions = []
    state.curCondition = null
}
const save = () => {
    let desc = "当:"
    if(Array.isArray(conditionConfig.conditions) && conditionConfig.conditions.length > 0){
        conditionConfig.conditions?.forEach((c:ConditionItemType,index:number,self:any[])=>{
            desc += `${c.label} ${getOptName(c.operator)} ${getValName(c.val)}`
            if(index < self.length - 1){
                desc += " 且 "
            }
        })
    }else{
        desc = "" //默认分支
    }

    state.lf?.setProperties( 
        state.activeNode.id,
        {
            ...conditionConfig,
            desc
        }
    )
    handleCancle()
}


const addCondition = ()=>{
    conditionConfig.conditions.push({id:getUUID()})
}
const deleteCondition = (id:string | number)=>{
    conditionConfig.conditions.splice(conditionConfig.conditions.findIndex(item=>item.id === id),1)
}

const onConditionChange = (v:any,condition:ConditionItemType)=>{
    let res = null
    for (let index = 0; index < state.conditionOptions.length; index++) {
        const item = state.conditionOptions[index];
        if(item.name === v){
            res = item
        }
    }
    condition.operators = res.operators
    condition.label = res.label
}
const selectOrgRoleUser = (condition:any)=>{
    selectOrgRoleUserRef.value?.handleOpen(condition.val)
    state.curCondition = condition
}

const getSelected  = (v:any)=>{
    state.curCondition!.val = v
}

const handleSwitchChange = (v:boolean)=>{
    if(v){
        conditionConfig.name = "默认条件"
    }else{
        conditionConfig.name = "条件节点"
    }
}

defineExpose({
    handleOpen
})
</script>

<style lang='scss' scoped>
.flow-btn-box {
    display: flex;
    justify-content: end;
    gap: 12px;
}

.condition-drawer-content {
    overflow: auto;
    overflow-y: auto;
    scrollbar-gutter: stable;
    overflow-x: hidden;
    height: 100%;

    &::-webkit-scrollbar {
        width: 6px;
        background: transparent;
        opacity: 0;
        transition: opacity 0.3s;
    }

    &:hover::-webkit-scrollbar {
        opacity: 1;
    }

    &::-webkit-scrollbar-corner,
    &::-webkit-scrollbar-thumb,
    &::-webkit-scrollbar-track {
        border-radius: 4px;
    }

    &::-webkit-scrollbar-corner,
    &::-webkit-scrollbar-track {
        background-color: transparent;
    }

    &::-webkit-scrollbar-thumb {
        background-color: transparent;
    }

    &:hover::-webkit-scrollbar-thumb {
        background-color: #a19e9e;

        &:hover {
            background-color: #ccc;
        }
    }
}
:deep(.ant-card){
    overflow: hidden;
}
:deep(.ant-card-body){
    padding: 0;
}
.condition-group-list{
    .condition-group-item{
        width: 100%;
        .condition-group-item-title{
            width: 100%;
            padding: 5px 10px;
            background-color: #f4f6f8;;
        }
        .condition-list{
            padding: 5px 10px;
            .condition-item{
                .condition-item-title{
                    color: #7b7a7a;
                }
            }
        }
    }
}
</style>